// pages/my/chatroom/room/room.js
const TIM = require("../../../../components/tim/tim-wx");
const util = require('../../../../utils/util');
const requestUtil = require('../../../../utils/request');
const api = require('../../../../config/api');
const timConst = require("../../../../config/const");
const app = getApp();

let tim = wx.$TIM;


Page({

  /**
   * 页面的初始数据
   */
  data: {
    messageList: [],
    nextReqMessageID: '',
    isCompleted: false,
    inputValue: '',
    CustomBar: 0,
    scrollTop: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let conversationID = options.id;
    this.setData({
      CustomBar: app.globalData.CustomBar,
      conversationID: conversationID,
      custId: options.id.slice(3)
    })
    this.im_on();
    this.getMessageList();
  },

  onReady: function () {
    this.setMessageRead();
  },

  /**
   * 下拉触顶事件
   */
  onRefresh: function () {
    if (!this.data.isCompleted) {
      this.getMessageList(true);
    } else {
      util.showToast('没有更多记录了');
    }
  },

  /**
   * 获取会话详情
   */
  getMessageList: function (flag = false) {
    let _this = this;
    if (!flag) {
      let promise = tim.getMessageList({
        conversationID: _this.data.conversationID,
        count: 15
      });
      promise.then(function (imResponse) {
        const messageList = imResponse.data.messageList; // 消息列表。
        const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
        const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
        for (let list of messageList) {
          let num = util.subtractTimeStampToDay(list.time, Date.parse(new Date()) / 1000);
          if (num == 0) {
            list.trueTime = util.formatMinDay(new Date(list.time * 1000));
          } else {
            list.trueTime = util.formatTimeNoSecond(new Date(list.time * 1000));
          }
        }
        _this.setData({
          messageList,
          nextReqMessageID,
          isCompleted
        })
        _this.setBottom();
      });
    } else {
      let promise = tim.getMessageList({
        conversationID: _this.data.conversationID,
        nextReqMessageID: _this.data.nextReqMessageID,
        count: 15
      });
      promise.then(function (imResponse) {
        const messageList = imResponse.data.messageList; // 消息列表。
        const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
        const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
        for (let mes of messageList) {
          let num = util.subtractTimeStampToDay(mes.time, Date.parse(new Date()) / 1000);
          if (num == 0) {
            mes.trueTime = util.formatMinDay(new Date(mes.time * 1000));
          } else {
            mes.trueTime = util.formatTimeNoSecond(new Date(mes.time * 1000));
          }
        }
        let list = _this.data.messageList;
        list.push(...messageList);
        _this.setData({
          messageList: list,
          nextReqMessageID,
          isCompleted
        })
        _this.setBottom();
      });
    }
  },

  /**
   * 更新事件跳入这里，获取list并添加到data里
   */
  setMessageList: function (list) {
    let _this = this;
    for (let l of list) {
      let num = util.subtractTimeStampToDay(l.time, Date.parse(new Date()) / 1000);
      if (num == 0) {
        l.trueTime = util.formatMinDay(new Date(l.time * 1000));
      } else {
        l.trueTime = util.formatTimeNoSecond(new Date(l.time * 1000));
      }
    }
    let messageList = _this.data.messageList;
    messageList.push(...list);
    _this.setData({
      messageList: messageList
    })
    _this.setBottom();
  },

  /**
   * 设置所有未读消息已读
   */
  setMessageRead: function () {
    let _this = this;
    let promise = tim.setMessageRead({
      conversationID: _this.data.conversationID
    });
    promise.then(function (imResponse) {
      // 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
      console.log('----------设置已读成功')
    }).catch(function (imError) {
      // 已读上报失败
      console.warn('setMessageRead error:', imError);
    });
  },

  /**
   * 获取焦点
   */
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

  /**
   * 创建文本消息
   * 
   */
  createTextMessage: function () {
    let message = tim.createTextMessage({
      to: this.data.custId,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: {
        text: this.data.inputValue
      },
    });
    this.sendMessage(message)
  },

  /**
   * 发送消息
   */
  sendMessage: function (message) {
    let _this = this;
    let promise = tim.sendMessage(message);
    promise.then(res => {
      console.log('----------发送成功', res)
      if (res.code == 0) {
        // 如果发送文本信息，则清空输入框
        if (res.data.message.type == TIM.TYPES.MSG_TEXT) {
          _this.setData({
            inputValue: ''
          });
          let mes = res.data.message;
          let num = util.subtractTimeStampToDay(mes.time, Date.parse(new Date()) / 1000);
          if (num == 0 || num == -1) {
            mes.trueTime = util.formatMinDay(new Date(mes.time * 1000));
          } else {
            mes.trueTime = util.formatTimeNoSecond(new Date(mes.time * 1000));
          }
          let list = _this.data.messageList;
          list.push(mes)
          _this.setData({
            messageList: list
          })
          _this.setBottom();
        }
      }
    }).catch(error => {
      console.error('----------发送消息失败', error)
    })
  },

  setBottom: function () {
    // 设置屏幕自动滚动到最后一条消息处
    let that = this;
    wx.createSelectorQuery().select('#viewMessageBody').boundingClientRect(function (rect) {
      wx.pageScrollTo({
        scrollTop: rect.height,
        duration: 100 // 滑动速度
      })
      that.setData({
        scrollTop: rect.height - that.data.scrollTop
      });
    }).exec();
  },

  /**
   * 监听IM是否启动
   */
  im_on: function () {
    let _this = this;
    console.log('监听IM中-------------------------');
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, (event) => {
      // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
      // event.name - TIM.EVENT.MESSAGE_RECEIVED
      // event.data - 存储 Message 对象的数组 - [Message]
      console.log('----------收到推送的单聊、群聊、群提示、群系统通知的新消息', event.data)
      console.log('3');
      _this.setMessageList(event.data)
    })
  },
})